<?php
declare (strict_types = 1);

namespace app\controller\clean;
use app\BaseController;
use app\logic\FileLogic;
use app\logic\ProjectLogic;
use think\response\Json;

class Projects extends BaseController
{

    public function __construct(\think\App $app){
        parent::__construct($app);
    }

    /**
     * 清洗批次列表
     * @return \think\response\Json
     */
    public function list()
    {
        $list = ProjectLogic::ins()->getProjectList();
        return json(successMsg('ok',$list));
    }

    /**
     * 添加清洗批次
     * @return \think\response\Json
     */
    public function add()
    {
        $title = $this->request->param('title/s', '', 'trim');
        $msg = ProjectLogic::ins()->addProject( $title);

        return json($msg);
    }

    /**
     * 上传清洗批次要素表 | 下载简要要素表模版
     * @return \think\response\Json
     */
    public function uploadCasesDetail() 
    {
        $this->request->fhUuid = $this->request->param('_uuid_','');
        $projectInfo = ProjectLogic::ins()->getProjectInfo($this->request->fhUuid);
        if(empty($projectInfo))
        {
            return json(errorMsg('请求参数_uuid_有误'));
        }
        // 优先下载简要要素表模版
        if ($this->request->param('download') === 'tpl') {
            $data = [['甲方标识','姓名','代偿本金','回购本金','贷款人关键字','担保公司关键字','反担保关键字','案件承办人','案件律师']];
            FileLogic::ins()->downExeclFile($data, '洋钱罐案件清洗要素表模板-' . date('YmdHis'));
            exit();
        }
        
        try {
            $file = $this->request->file('file');
            if (!$file->isValid()) {
                return json(errorMsg('上传失败'));
            }
        } catch (\Throwable $e) {
            return json(errorMsg($e->getMessage()));
        }
        
        $extension = $file->getOriginalExtension();
        if ($extension !== 'xlsx') {
            return json(errorMsg('当前文件格式错误,仅支持XLSX文件'));
        }
        
        $fileData = FileLogic::ins()->getExeclCon($file->getPathname());
        //保存Excel数据
        $saveResult = ProjectLogic::ins()->saveExcelData($fileData,$this->request->fhUuid);
        if($saveResult === true){
            // 保存成功后直接开始清洗任务
            // $cleanResult = ProjectLogic::ins()->addChangeFileStream($this->request->fhUuid,$projectInfo);
            // return json($cleanResult);
            return json(successMsg('元素表上传成功'));
        }else{
            return json($saveResult);
        }
    }

}
